package spring.cloud.tasks.api.analyzer;

import spring.cloud.tasks.api.domain.zooKeeperClusterAndNameSpace.NameSpaceConfiguration;
import spring.cloud.tasks.common.node.TaskNodePath;
import spring.cloud.tasks.common.zookeeper.ZooKeeper;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class TaskStatisticsAnalyzer {

    private final Map<String/** {taskId}-{domain} */, TaskStatistics> taskKeyToTaskStatisticsMap = new ConcurrentHashMap<>();

    public TaskStatistics analyzeTaskStatistics(ZooKeeper zooKeeper, NameSpaceConfiguration nameSpaceConfiguration, String taskId, ExecutorInfoAnalyzer executorInfoAnalyzer) throws Exception {
        String jobDomainKey = nameSpaceConfiguration.getNameSpace() + "-" + taskId;
        TaskStatistics taskStatistics = taskKeyToTaskStatisticsMap.get(jobDomainKey);
        if (taskStatistics == null) {
            taskStatistics = new TaskStatistics(nameSpaceConfiguration.getNameSpace(), taskId);
            taskKeyToTaskStatisticsMap.put(jobDomainKey, taskStatistics);
        }
        // loadLevel of this job
        int loadLevel = Integer.parseInt(zooKeeper.getData(TaskNodePath.getTaskConfigurationNodePath(taskId, "loadLevel")));
        int shardingTotalCount = Integer.parseInt(zooKeeper.getData(TaskNodePath.getTaskConfigurationNodePath(taskId, "shardingTotalCount")));
        List<String> executorIdList = null;
        if (zooKeeper.checkExists(TaskNodePath.getTaskExecutorsNodePath(taskId))) {
            executorIdList = zooKeeper.getChildren(TaskNodePath.getTaskExecutorsNodePath(taskId));
            executorInfoAnalyzer.analyzeTaskExecutor(zooKeeper, nameSpaceConfiguration, executorIdList, taskId, loadLevel, taskStatistics);
        }

        taskStatistics.setTotalLoadLevel(loadLevel * shardingTotalCount);
        taskKeyToTaskStatisticsMap.put(jobDomainKey, taskStatistics);
        return taskStatistics;
    }

    public List<TaskStatistics> getTaskStatisticsList() {
        return new ArrayList<TaskStatistics>(taskKeyToTaskStatisticsMap.values());
    }
}
